
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import facebook
import logging
import config
from google.appengine.api import urlfetch
from xml.dom.minidom import parseString
from urllib import urlencode

facebook_api_key = config.facebook_api_key
facebook_secret_key = config.facebook_secret_key
amazon_key = config.amazon_key
amazon_ref = config.amazon_ref

def getText(n):
    rc = ""
    for node in n.childNodes:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

class Item(db.Model):
    owner = db.StringProperty()

class home(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates', 'home.html')
        self.response.out.write(template.render(path, {"title":"Inventorier", "api_key":facebook_api_key}))

class search(webapp.RequestHandler):
    def get(self):
        upc = self.request.get('upc')
        #amazon_req = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=%s&AssociateTag=%s&Version=2006-09-11&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&UPC=%s" % (amazon_key, amazon_ref, upc)
        #amazon_req = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=" + amazon_key + "&Operation=ItemSearch&SearchIndex=Books&Title=Harry%20Potter&Version=2008-08-19"
        #amazon_req = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=" + amazon_key + "&Operation=ItemLookup&IdType=ISBN&SearchIndex=Books&ItemId=" + upc
        amazon_req = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=" + amazon_key + "&Operation=ItemSearch&SearchIndex=All&Keywords=" + upc
        
        result = urlfetch.fetch(amazon_req)
        dom = parseString(result.content)
        itemsNode = dom.getElementsByTagName("Items")[0]
        itemNodes = dom.getElementsByTagName("Item")
        items = []
        for itemNode in itemNodes:
            items.append({"asin":getText(itemNode.getElementsByTagName("ASIN")[0]),
                          "title":getText(itemNode.getElementsByTagName("ItemAttributes")[0].getElementsByTagName("Title")[0])})
        path = os.path.join(os.path.dirname(__file__), 'templates', 'search.html')
        self.response.out.write(template.render(path, {"title":"Inventorier - Search", "api_key":facebook_api_key, "upc":upc, "items":items, "result":result}))
        
application = webapp.WSGIApplication(
                                     [('/', home),
                                      ('/search', search)],
                                     debug=True)

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == "__main__": 
    main()
